<template>
  <h1 ref="title">hello vue3</h1>
  <p>{{ count }}</p>
  <p>{{ times }}</p>
  <button @click="handleClick">更新</button>

  <p>{{ person.name }} - {{ person.age }}</p>
  <button @click="handleClick1">更新age</button>

  <Child :count="count" @update="handleClick" />
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  watch,
  computed,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
} from "vue";
import Child from "./Child.vue";

export default defineComponent({
  name: "App",
  components: {
    Child,
  },
  setup() {
    // setup函数一上来就会触发
    // 相当于 beforeCreate created
    // 同一个生命周期可以绑定多个
    onBeforeUnmount(() => {});

    onMounted(() => {
      console.log(111);
    });
    onMounted(() => {
      console.log(222);
    });
    onMounted(() => {
      console.log(333);
      console.log(title.value);
    });

    const title = ref();

    // 在setup函数中不能使用this
    // console.log(this); // undefined

    /******************** xxx功能开始 **********************/
    // 1. 定义响应式数据 data
    // ref(数据的初始化值) 返回值就是响应式数据（定义单个响应式数据）
    const count = ref(0);
    const persons = ref<{ id: number; name: string }[]>([]);
    // 2. 定义方法 methods
    const handleClick = () => {
      // console.log(111);
      // ref数据在setup函数中，需要xxx.value访问
      // ref数据模板页面中，直接xxx访问
      count.value++;
      // persons.value.push({ id: 1, name: "jack" });
    };

    watch(
      count,
      (newVal, oldVal) => {
        console.log(newVal, oldVal);
      },
      {
        // immediate: true, deep: true
      }
    );

    // 只读
    const times = computed(() => {
      return count.value + "次";
    });
    // 可读可写
    // const xxx = computed({
    //   get() {},
    //   set() {}
    // })

    /******************** xxx功能结束 **********************/

    // 定义多个响应式数据（表单项数据）
    // 解构出来属性失去响应式
    const person = reactive<{ name: string; age: number }>({
      name: "jack",
      age: 18,
    });
    const handleClick1 = () => {
      // reactive定义数据直接操作
      person.age++;
    };

    // setup函数返回值，模板页面才能访问到
    return {
      count,
      handleClick,
      handleClick1,
      person,
      times,
      title,
    };
  },
});
</script>

<style scoped></style>
